package com.apchernykh.rozhlasapp.services;

import com.apchernykh.rozhlasapp.interfaces.IPhoneStateListener;
import com.apchernykh.rozhlasapp.interfaces.IScreenStateListener;
import com.apchernykh.rozhlasapp.utils.ConditionalLog;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public abstract class PhoneInetNotifiedService extends InetNotifiedService
		implements IPhoneStateListener, IScreenStateListener {
	private TelephonyManager mTelephonyManager;
	private PhoneStateListener mListener;

	public class ScreenReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context iContext, Intent iIntent) {
			if (iIntent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
				ConditionalLog.e("SCREEN OFF");
				onScreenOff();
			} else if (iIntent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
				ConditionalLog.e("SCREEN ON");
				onScreenOn();
			}
		}
	}

	BroadcastReceiver mScreenOnReceiver = new ScreenReceiver();

	@Override
	public void onCreate() {

		IntentFilter aFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
		aFilter.addAction(Intent.ACTION_SCREEN_OFF);
		registerReceiver(mScreenOnReceiver, aFilter);

		if (mListener == null) {
			Object aTelephonyServiceObj = getSystemService(TELEPHONY_SERVICE);
			if (aTelephonyServiceObj != null
					&& aTelephonyServiceObj instanceof TelephonyManager) {
				mTelephonyManager = (TelephonyManager) aTelephonyServiceObj;
				// Create a PhoneStateListener to watch for off-hook and idle
				// events
				mListener = new PhoneStateListener() {
					@Override
					public void onDataConnectionStateChanged(int state,
							int networkType) {
						// We have changed proticols, for example we have gone
						// from
						// HSDPA to GPRS
						// HSDPA is an example of a 3G connection
						// GPRS is an example of a 2G connection
					}

					@Override
					public void onCallStateChanged(int iState,
							String iIncomingCLID) {
						switch (iState) {
						case TelephonyManager.CALL_STATE_OFFHOOK:
						case TelephonyManager.CALL_STATE_RINGING:
							pausePlaybackOnIncomingCall();
							break;
						case TelephonyManager.CALL_STATE_IDLE:
							resumePlaybackOnPhoneHangUp();
							break;
						}
					}
				};

				// Register the listener with the telephony manager.
				mTelephonyManager.listen(mListener,
						PhoneStateListener.LISTEN_CALL_STATE);
			}
		}
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		if (mTelephonyManager != null) {
			mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_NONE);
			mListener = null;
			mTelephonyManager = null;
		}
		unregisterReceiver(mScreenOnReceiver);
		super.onDestroy();
	}
}